package com.mall.shopping.services;

import com.mall.commons.tool.exception.ValidateException;
import com.mall.commons.tool.redisconfig.RedissonAutoConfiguration;
import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dal.persistence.PanelMapper;
import com.mall.shopping.dto.*;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.Redisson;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @description:
 * @author:
 * @date:
 */
@Service
public class ICartServiceImpl implements ICartService {
    private static RedissonClient redisson = Redisson.create();

    @Autowired
    ItemMapper itemMapper;

    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {
        CartListByIdResponse response = new CartListByIdResponse();
        try {
            //参数校验
            request.requestCheck();
            // TODO 不知道redis里product对象用哪个实体类，先用CartProductDto
            RMap<Long, CartProductDto> map = redisson.getMap(String.valueOf(request.getUserId()));

            List<CartProductDto> cartProductDtos = new ArrayList<>(map.values());

            response.setCartProductDtos(cartProductDtos);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (ValidateException e) {
            response.setCode(ShoppingRetCode.PARAMETER_VALIDATION_FAILED.getCode());
            response.setMsg(ShoppingRetCode.PARAMETER_VALIDATION_FAILED.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
            response.setMsg(ShoppingRetCode.DB_EXCEPTION.getMessage());
        }
        return response;

    }

    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        AddCartResponse response = new AddCartResponse();
        try {
            //参数校验
            request.requestCheck();
            // TODO 不知道redis里product对象用哪个实体类，先用CartProductDto
            RMap<Long, CartProductDto> map = redisson.getMap(String.valueOf(request.getUserId()));

            //测试购物车的数量“是否”大于库存数量或限制购买数量
            Long itemId = request.getProductId();
            Integer goodsNum = request.getProductNum();
            Item item1 = itemMapper.selectByPrimaryKey(itemId);

            //商品限购
            if (goodsNum > item1.getLimitNum()) {
                response.setCode(ShoppingRetCode.GOODS_LIMIT.getCode());
                response.setMsg(ShoppingRetCode.GOODS_LIMIT.getMessage());
                return response;
            }

            //库存数量不足
            if (goodsNum > item1.getNum()) {
                response.setCode(ShoppingRetCode.INVENTORY_LIMIT.getCode());
                response.setMsg(ShoppingRetCode.INVENTORY_LIMIT.getMessage());
                return response;
            }


            CartProductDto cartTest = map.get(itemId);
            CartProductDto cartProductDto = new CartProductDto();

            //如果购物车没有该商品
            if (cartTest == null) {
                Item item = itemMapper.selectById(itemId);
                cartProductDto.setChecked("true");
                cartProductDto.setLimitNum(item.getLimitNum().longValue());
                cartProductDto.setProductId(itemId);
                cartProductDto.setProductImg(item.getImageBig());
                cartProductDto.setProductName(item.getTitle());
                cartProductDto.setProductNum(goodsNum.longValue());
                cartProductDto.setSalePrice(item.getPrice());
                map.put(itemId, cartProductDto);
            }
            //如果购物车有该商品
            else {
                //商品限购
                if (cartTest.getProductNum() + goodsNum > item1.getLimitNum()) {
                    response.setCode(ShoppingRetCode.GOODS_LIMIT.getCode());
                    response.setMsg(ShoppingRetCode.GOODS_LIMIT.getMessage());
                    return response;
                }

                //库存数量不足
                if (cartTest.getProductNum() + goodsNum > item1.getNum()) {
                    response.setCode(ShoppingRetCode.INVENTORY_LIMIT.getCode());
                    response.setMsg(ShoppingRetCode.INVENTORY_LIMIT.getMessage());
                    return response;
                }

                cartTest.setProductNum(cartTest.getProductNum() + goodsNum);
                response.setCode(ShoppingRetCode.SUCCESS.getCode());
                response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            }
        } catch (
                Exception e) {
            e.printStackTrace();
            response.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
            response.setMsg(ShoppingRetCode.DB_EXCEPTION.getMessage());
        }
        return response;

    }

    /**
     * zhiMing 2021年12月13日 09点23分
     * 更新购物车中商品的数量
     *
     * @param request
     * @return
     */
    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        UpdateCartNumResponse response = new UpdateCartNumResponse();
        try {
            //参数校验
            request.requestCheck();

            //测试购物车的数量“是否”大于库存数量或限制购买数量
            Long itemId = request.getItemId();
            Integer goodsNum = request.getNum();
            Item item1 = itemMapper.selectByPrimaryKey(itemId);

            //商品限购
            if (goodsNum > item1.getLimitNum()) {
                response.setCode(ShoppingRetCode.GOODS_LIMIT.getCode());
                response.setMsg(ShoppingRetCode.GOODS_LIMIT.getMessage());
                return response;
            }

            //库存数量不足
            if (goodsNum > item1.getNum()) {
                response.setCode(ShoppingRetCode.INVENTORY_LIMIT.getCode());
                response.setMsg(ShoppingRetCode.INVENTORY_LIMIT.getMessage());
                return response;
            }

            // TODO 不知道redis里product对象用哪个实体类，先用CartProductDto
            RMap<Long, CartProductDto> map = redisson.getMap(String.valueOf(request.getUserId()));
            //先遍历拿到productId对应的对象，修改后再写会去
            for (Long productId : map.keySet()) {
                if (productId.compareTo(request.getItemId()) == 0) {
                    CartProductDto cartProductDto = map.get(productId);
                    cartProductDto.setChecked(request.getChecked());
                    cartProductDto.setProductNum(request.getNum().longValue());
                    map.put(productId, cartProductDto);
                }
            }
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (ValidateException e) {
            response.setCode(ShoppingRetCode.PARAMETER_VALIDATION_FAILED.getCode());
            response.setMsg(ShoppingRetCode.PARAMETER_VALIDATION_FAILED.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
            response.setMsg(ShoppingRetCode.DB_EXCEPTION.getMessage());
        }
        return response;
    }

    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        CheckAllItemResponse response = new CheckAllItemResponse();
        try {
            request.requestCheck();
            RMap<Long, CartProductDto> map = redisson.getMap(String.valueOf(request.getUserId()));
            Collection<CartProductDto> productDtos = map.values();
            for (CartProductDto productDto : productDtos) {
                productDto.setChecked(request.getChecked());
                map.put(productDto.getProductId(), productDto);
            }
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (ValidateException e) {
            response.setCode(ShoppingRetCode.PARAMETER_VALIDATION_FAILED.getCode());
            response.setMsg(ShoppingRetCode.PARAMETER_VALIDATION_FAILED.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
            response.setMsg(ShoppingRetCode.DB_EXCEPTION.getMessage());
        }
        return response;
    }

    /**
     * zhiMing 2021年12月13日 14点02分
     * 删除购物车中的商品
     *
     * @param request
     * @return
     */
    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
        DeleteCartItemResponse response = new DeleteCartItemResponse();
        try {
            request.requestCheck();
            RMap<Long, CartProductDto> map = redisson.getMap(String.valueOf(request.getUserId()));
            map.remove(request.getItemId());
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (ValidateException e) {
            response.setCode(ShoppingRetCode.PARAMETER_VALIDATION_FAILED.getCode());
            response.setMsg(ShoppingRetCode.PARAMETER_VALIDATION_FAILED.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
            response.setMsg(ShoppingRetCode.DB_EXCEPTION.getMessage());
        }
        return response;
    }

    /**
     * zhiMing 2021年12月13日 14点31分
     * 删除选中的商品
     *
     * @param request
     * @return
     */
    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {
        DeleteCheckedItemResposne response = new DeleteCheckedItemResposne();
        try {
            request.requestCheck();
            RMap<Long, CartProductDto> map = redisson.getMap(String.valueOf(request.getUserId()));
            Collection<CartProductDto> cartProductDtos = map.values();
            for (CartProductDto productDto : cartProductDtos) {
                //TODO 删除的值我理解为字符串类型的true 和 false
                if ("true".equals(productDto.getChecked())) {
                    map.remove(productDto.getProductId());
                }
            }
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (ValidateException e) {
            response.setCode(ShoppingRetCode.PARAMETER_VALIDATION_FAILED.getCode());
            response.setMsg(ShoppingRetCode.PARAMETER_VALIDATION_FAILED.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
            response.setMsg(ShoppingRetCode.DB_EXCEPTION.getMessage());
        }
        return response;
    }

    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        return null;
    }
}
